from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.conf import settings
import requests
import json
import uuid
from datetime import datetime
from .models import ImageGeneration


def image_list(request):
    """AI图像生成列表"""
    images = ImageGeneration.objects.all().order_by('-created_at')
    return render(request, 'ai_image/image_list.html', {
        'images': images
    })


@login_required
def create_image(request):
    """AI图像生成表单"""
    if request.method == 'POST':
        prompt = request.POST.get('prompt')
        negative_prompt = request.POST.get('negative_prompt', '')
        style = request.POST.get('style')
        width = int(request.POST.get('width', 512))
        height = int(request.POST.get('height', 512))
        
        if prompt and style:
            user = request.user
            
            ImageGeneration.objects.create(
                user=user,
                prompt=prompt,
                negative_prompt=negative_prompt,
                style=style,
                width=width,
                height=height
            )
            messages.success(request, '图像生成任务已创建！')
            return redirect('ai_image:image_list')
        else:
            messages.error(request, '请填写提示词和选择风格')
    
    return render(request, 'ai_image/create_image.html')


@login_required
@csrf_exempt
@never_cache
@require_http_methods(["POST"])
def generate_image_api(request):
    """火山引擎 AI 图像生成 API"""
    try:
        # 获取请求参数
        if request.content_type == 'application/json':
            data = json.loads(request.body)
        else:
            # 支持 form data
            data = {
                'prompt': request.POST.get('prompt', ''),
                'image_size': request.POST.get('image_size', '1024x1024'),
                'num_images': int(request.POST.get('num_images', 1))
            }
            
        prompt = data.get('prompt', '').strip()
        
        # 校验参数
        if not prompt:
            return JsonResponse({
                'success': False, 
                'error': '提示词不能为空'
            })
        
        # 可选参数
        image_size = data.get('image_size', '1024x1024')  # 默认分辨率
        num_images = data.get('num_images', 1)  # 默认生成数量
        
        # 获取火山引擎配置
        volcengine_config = settings.VOLCENGINE_AI_CONFIG
        
        # 准备请求数据
        request_data = {
            "model": volcengine_config['MODEL_ID'],
            "prompt": prompt,
            "n": min(num_images, 4),  # 限制最大生成数量
            "size": image_size,
            "response_format": "url"
        }
        
        # 请求头
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {volcengine_config["API_KEY"]}'
        }
        
        # 发送请求到火山引擎
        response = requests.post(
            volcengine_config['API_URL'],
            headers=headers,
            json=request_data,
            timeout=60
        )
        
        if response.status_code == 200:
            result = response.json()
            
            # 保存到数据库
            user = request.user
            
            image_generation = ImageGeneration.objects.create(
                user=user,
                prompt=prompt,
                width=int(image_size.split('x')[0]),
                height=int(image_size.split('x')[1]),
                status='processing'  # 先设为处理中
            )
            
            # 下载并保存图片到本地
            images_data = []
            if result.get('data'):
                for i, img_data in enumerate(result['data']):
                    try:
                        # 下载图片
                        img_url = img_data['url']
                        img_response = requests.get(img_url, timeout=30)
                        
                        if img_response.status_code == 200:
                            # 保存到media目录
                            import os
                            from django.core.files.base import ContentFile
                            from django.core.files.storage import default_storage
                            
                            # 生成文件名
                            filename = f"generated_images/image_{image_generation.id}_{i+1}.jpg"
                            
                            # 保存文件
                            file_path = default_storage.save(filename, ContentFile(img_response.content))
                            
                            # 更新数据库记录
                            if i == 0:  # 第一张图片保存到主记录
                                image_generation.image_url = f"/media/{file_path}"
                                image_generation.status = 'completed'
                                image_generation.save()
                            
                            # 添加到返回数据
                            images_data.append({
                                'url': f"{request.build_absolute_uri('/media/')}{file_path}",
                                'local_path': file_path
                            })
                        else:
                            print(f"下载图片失败: {img_response.status_code}")
                    except Exception as e:
                        print(f"处理图片时出错: {str(e)}")
                        continue
            
            # 如果没有成功下载任何图片，标记为失败
            if not images_data:
                image_generation.status = 'failed'
                image_generation.save()
                return JsonResponse({
                    'success': False,
                    'error': '图片下载失败'
                })
            
            # 返回成功结果
            return JsonResponse({
                'success': True,
                'message': '图像生成成功',
                'data': {
                    'generation_id': image_generation.id,
                    'prompt': prompt,
                    'images': images_data,
                    'created_at': image_generation.created_at.isoformat()
                }
            })
        else:
            # API 调用失败
            error_msg = f"API 调用失败: {response.status_code}"
            try:
                error_detail = response.json()
                error_msg += f" - {error_detail.get('error', {}).get('message', '')}"
            except:
                error_msg += f" - {response.text}"
                
            return JsonResponse({
                'success': False,
                'error': error_msg
            })
            
    except json.JSONDecodeError as e:
        return JsonResponse({
            'success': False,
            'error': f'请求数据格式错误: {str(e)}',
            'debug': f'Content-Type: {request.content_type}, Body: {request.body.decode("utf-8")[:200]}'
        })
    except requests.RequestException as e:
        return JsonResponse({
            'success': False,
            'error': f'网络请求失败: {str(e)}'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'服务器内部错误: {str(e)}'
        })


def volcengine_test_view(request):
    """火山引擎 AI 测试页面"""
    return render(request, 'ai_image/volcengine_test.html')


def image_display_test(request):
    """图片显示测试页面"""
    from django.http import FileResponse
    import os
    
    # 返回静态HTML文件
    file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_image_display.html')
    if os.path.exists(file_path):
        return FileResponse(open(file_path, 'rb'), content_type='text/html')
    else:
        return HttpResponse('测试文件不存在', status=404)


def image_gallery(request):
    """图片库查看页面"""
    from django.http import FileResponse
    import os
    
    # 返回图片库HTML文件
    file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'image_gallery.html')
    if os.path.exists(file_path):
        return FileResponse(open(file_path, 'rb'), content_type='text/html')
    else:
        return HttpResponse('图片库文件不存在', status=404)


@login_required
def image_proxy(request, image_id):
    """图片代理服务 - 解决跨域访问问题"""
    try:
        # 从数据库获取图片记录
        image_generation = ImageGeneration.objects.get(id=image_id)
        
        if image_generation.image_url:
            # 直接返回本地文件
            import os
            from django.conf import settings
            
            # 从数据库URL提取文件路径
            file_path = image_generation.image_url.replace('/media/', '')
            full_path = os.path.join(settings.MEDIA_ROOT, file_path)
            
            if os.path.exists(full_path):
                # 读取文件并返回
                with open(full_path, 'rb') as f:
                    file_data = f.read()
                
                response = HttpResponse(file_data, content_type='image/jpeg')
                response['Content-Disposition'] = f'inline; filename="generated_image_{image_id}.jpg"'
                return response
            else:
                return HttpResponse('图片文件不存在', status=404)
        else:
            return HttpResponse('图片URL不存在', status=404)
            
    except ImageGeneration.DoesNotExist:
        return HttpResponse('图片记录不存在', status=404)
    except Exception as e:
        return HttpResponse(f'服务器错误: {str(e)}', status=500)


@login_required
@csrf_exempt
@never_cache
@require_http_methods(["GET"])
def image_list_api(request):
    """图像列表API接口"""
    try:
        # 获取查询参数
        page = int(request.GET.get('page', 1))
        page_size = min(int(request.GET.get('page_size', 20)), 100)  # 限制最大页面大小
        user_id = request.GET.get('user_id')
        status = request.GET.get('status')
        
        # 构建查询
        queryset = ImageGeneration.objects.all().order_by('-created_at')
        
        if user_id:
            queryset = queryset.filter(user_id=user_id)
        if status:
            queryset = queryset.filter(status=status)
        
        # 分页计算
        total_count = queryset.count()
        start_index = (page - 1) * page_size
        end_index = start_index + page_size
        images = queryset[start_index:end_index]
        
        # 序列化数据
        images_data = []
        for img in images:
            images_data.append({
                'id': img.id,
                'prompt': img.prompt,
                'negative_prompt': img.negative_prompt,
                'style': img.style,
                'width': img.width,
                'height': img.height,
                'status': img.status,
                'image_url': img.image_url,
                'user': img.user.username,
                'created_at': img.created_at.isoformat(),
                'updated_at': img.updated_at.isoformat()
            })
        
        return JsonResponse({
            'success': True,
            'data': {
                'images': images_data,
                'pagination': {
                    'page': page,
                    'page_size': page_size,
                    'total_count': total_count,
                    'total_pages': (total_count + page_size - 1) // page_size
                }
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'获取图像列表失败: {str(e)}'
        })


@login_required
@csrf_exempt
@never_cache
@require_http_methods(["GET", "DELETE"])
def image_detail_api(request, image_id):
    """图像详情API接口"""
    try:
        image_generation = ImageGeneration.objects.get(id=image_id)
        
        if request.method == 'GET':
            # 获取图像详情
            return JsonResponse({
                'success': True,
                'data': {
                    'id': image_generation.id,
                    'prompt': image_generation.prompt,
                    'negative_prompt': image_generation.negative_prompt,
                    'style': image_generation.style,
                    'width': image_generation.width,
                    'height': image_generation.height,
                    'status': image_generation.status,
                    'image_url': image_generation.image_url,
                    'user': image_generation.user.username,
                    'created_at': image_generation.created_at.isoformat(),
                    'updated_at': image_generation.updated_at.isoformat()
                }
            })
            
        elif request.method == 'DELETE':
            # 删除图像记录和文件
            if image_generation.image_url:
                import os
                from django.conf import settings
                
                # 删除本地文件
                file_path = image_generation.image_url.replace('/media/', '')
                full_path = os.path.join(settings.MEDIA_ROOT, file_path)
                
                if os.path.exists(full_path):
                    try:
                        os.remove(full_path)
                    except OSError:
                        pass  # 文件删除失败，继续删除数据库记录
            
            # 删除数据库记录
            image_generation.delete()
            
            return JsonResponse({
                'success': True,
                'message': '图像删除成功'
            })
            
    except ImageGeneration.DoesNotExist:
        return JsonResponse({
            'success': False,
            'error': '图像记录不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'操作失败: {str(e)}'
        })
